package com.greatmay.webapp.action;

import java.util.List;

import com.greatmay.dao.SearchException;
import com.greatmay.model.Express;
import com.greatmay.service.ExpressService;
import com.opensymphony.xwork2.Preparable;

public class ExpressAction extends BaseAction implements Preparable {
	private static final long serialVersionUID = 7832211898458898566L;
	private ExpressService expressService;
    private List expresses;
    private Express express;
    private Long id;
    private String query;

    public void setExpressService(ExpressService expressService) {
        this.expressService = expressService;
    }

    public List getExpresses() {
        return expresses;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String expressId = getRequest().getParameter("express.id");
            if (expressId != null && !expressId.equals("")) {
                express = expressService.get(new Long(expressId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        try {
            expresses = expressService.search(query, Express.class);
        } catch (SearchException se) {
            addActionError(se.getMessage());
            expresses = expressService.getAll();
        }
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Express getExpress() {
        return express;
    }

    public void setExpress(Express express) {
        this.express = express;
    }

    public String delete() {
    	expressService.remove(express.getId());
        saveMessage(getText("express.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            express = expressService.get(id);
        } else {
            express = new Express();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (express.getId() == null);

        expressService.save(express);

        String key = (isNew) ? "express.added" : "express.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}